package com.example.newsapp.model.repository;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;
import com.example.newsapp.model.entity.NewsData;
import com.example.newsapp.network.NewsApiService;
import com.example.newsapp.network.RetrofitClient;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class NewsRepository {
    private static final String TAG = "NewsRepository";
    private NewsApiService newsApiService;
    private MutableLiveData<NewsData> newsData = new MutableLiveData<>();
    private MutableLiveData<String> errorMessage = new MutableLiveData<>();

    public NewsRepository() {
        newsApiService = RetrofitClient.getInstance().getNewsApiService();
    }

    public MutableLiveData<NewsData> getNewsData() {
        return newsData;
    }

    public MutableLiveData<String> getErrorMessage() {
        return errorMessage;
    }

    public void getNewsList(String city, int page) {
        Call<NewsData> call = newsApiService.getNewsList(city, page);
        call.enqueue(new Callback<NewsData>() {
            @Override
            public void onResponse(Call<NewsData> call, Response<NewsData> response) {
                if (response.isSuccessful() && response.body() != null) {
                    newsData.setValue(response.body());
                } else {
                    errorMessage.setValue("获取新闻数据失败");
                }
            }

            @Override
            public void onFailure(Call<NewsData> call, Throwable t) {
                Log.d(TAG, "网络请求失败: "+ t.getMessage());
                errorMessage.setValue("网络请求失败: " + t.getMessage());
            }
        });
    }
}